package org.lisen.patterndemo.singleton;

/**
 * 单例模式： 懒汉式，线程安全，但性能较低
 */
public class SingletonDemo03 {

    private SingletonDemo03() {
        //模拟构造函数的运行耗时
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static SingletonDemo03 singletonDemo03 = null;

    public static  SingletonDemo03 getInstance(){
        //系统减小同步块来提升性能，可以吗？
        if(singletonDemo03 == null) {
            synchronized (SingletonDemo03.class) {
                //if(singletonDemo03 == null) {
                    singletonDemo03 = new SingletonDemo03();
                //}
            }
        }
        return singletonDemo03;
    }

    public String hello(String name) {
        return "hello " + name;
    }


    /*
     * 测试多线程下单例模式是否安全
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(()->{
                System.out.println(SingletonDemo03.getInstance().hashCode());
            }).start();
        }
    }

}
